import os
import sys
import numpy as np
import tensorflow as tf
from tensorflow import keras
import ssl

ssl._create_default_https_context = ssl._create_unverified_context
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
np.set_printoptions(linewidth=1000)

# 加载mnist数据，以numpy形式返回，分割为60000/10000两部分
(x, y), (x_val, y_val) = keras.datasets.mnist.load_data()
print('training dataset shape: ', x.shape, y.shape)  # (60000, 28, 28) (60000,)
print('testing  dataset shape: ', x_val.shape, y_val.shape)  # (10000, 28, 28) (10000,)

print('x[0] in training dataset: \n', x[0], sep='\t', end='\n', file=sys.stdout)

x = tf.convert_to_tensor(x, dtype=tf.float32) / 255.
y = tf.convert_to_tensor(y, dtype=tf.int32)

# one hot encoding
y = tf.one_hot(y, depth=10)
print('y after one hot encoding: ', y.shape)
print('y[0] after one hot encoding: ', y[0])

train_dataset = tf.data.Dataset.from_tensor_slices((x, y))
train_dataset = train_dataset.batch(100)
print(train_dataset)

model = keras.Sequential([
    keras.layers.Dense(512, activation='relu'),
    keras.layers.Dense(256, activation='relu'),
    keras.layers.Dense(10)])

optimizer = keras.optimizers.SGD(learning_rate=0.001)


def train_epoch(epoch):
    # Step4.loop
    for step, (x, y) in enumerate(train_dataset):

        with tf.GradientTape() as tape:
            # [b, 28, 28] => [b, 784]
            x = tf.reshape(x, (-1, 28 * 28))
            # Step1. compute output
            # [b, 784] => [b, 10]
            out = model(x)
            # Step2. compute loss
            loss = tf.reduce_sum(tf.square(out - y)) / x.shape[0]

        # Step3. optimize and update w1, w2, w3, b1, b2, b3
        grads = tape.gradient(loss, model.trainable_variables)
        # w' = w - lr * grad
        optimizer.apply_gradients(zip(grads, model.trainable_variables))

        if step % 100 == 0:
            print(epoch, step, 'loss:', loss.numpy())


def train():
    for epoch in range(30):
        train_epoch(epoch)


if __name__ == '__main__':
    train()
